package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.service.IBaseService;
import cn.itsource.basic.util.PageList;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

/**
 * 不能交给spring管理，只是公共的代码，运行的是具体的Service
 * @param <T>
 * @param <Q>
 */
@Transactional(readOnly = true,propagation= Propagation.SUPPORTS)
public class BaseServiceImpl<T extends BaseDomain,Q extends BaseQuery> implements IBaseService<T,Q> {

    /**
     * 注入mapper
     */
    @Autowired
    Mapper<T> baseMapper;

    @Override
    public T findOne(Long id) {
        return baseMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<T> findAll() {
        return baseMapper.selectAll();
    }

    @Override
    @Transactional
    public void saveOrUpdate(T t) {
        if (t.getId() == null){

            baseMapper.insertSelective(t);
        }else{
            baseMapper.updateByPrimaryKeySelective(t);
        }
    }

    @Override
    @Transactional
    public void delete(Long id) {
        baseMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageList<T> findPage(Q q) {
        //1.使用分页工具
        PageHelper.startPage(q.getPage(),q.getSize());
        //2.查询所有
        List<T> list = baseMapper.selectAll();
        //3.如果一条数据都没有，直接返回默认的total = 0 list是new ArrayList
        if (list.size() == 0){
            return new PageList<>();
        }
        //4.封装pageInfo
        PageInfo<T> pageInfo = new PageInfo<>(list);
        //5.返回有数据的分页对象
        return new PageList<>(pageInfo.getTotal(),pageInfo.getList());
    }

    @Transactional// 事务管理
    public void batchDelete(Long[] ids) {
        /**
         * 批量删除
         */
        if (ids.length == 0){
            return;
        }

        //iter:快速生成增强for循环的
        for (Long id : ids) {
            //删除
            baseMapper.deleteByPrimaryKey(id);
        }

    }
}
